//
//  QRCode.swift
//  SwiftCode
//
//  Created by yuhus on 2024/1/24.
//

import Foundation
import RxSwift
import AVFoundation

public enum QRCode {}

extension ObservableType {
  func dismiss(animated: Bool) -> Observable<Element> {
    return flatMapLatest { result -> Observable<Element> in
      return Single.create { single in
        if let navigationController = UIViewController.topMost {
          navigationController.dismiss(animated: animated) {
            single(.success(result))
          }
        } else {
          single(.success(result))
        }
        return Disposables.create()
      }
      .asObservable()
    }
  }
}

extension QRCode {
  static func presentNotAuthorized() {
    let title = "权限申请"
    let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? ""
    let message = #"未经相机许可，无法使用扫描功能!\#n\#n"设置" > "\#(appName)"#
    let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
    
    alert.addAction(.init(title: "知道了", style: .cancel, handler: { _ in
      print(#function, #line)
    }))
    
    alert.addAction(.init(title: "设置", style: .default, handler: { _ in
      guard let url = URL(string: UIApplication.openSettingsURLString),
            UIApplication.shared.canOpenURL(url as URL) else {
        return
      }
      UIApplication.shared.open(url)
    }))
    UIViewController.topMost?.present(alert, animated: true)
  }
  
  static func presentConfigurationFailed() {
    let message = NSLocalizedString("Unable to capture media", comment: "Alert message when something goes wrong during capture session configuration")
    let alertController = UIAlertController(title: "AVCam", message: message, preferredStyle: .alert)
    
    alertController.addAction(UIAlertAction(
      title: NSLocalizedString("OK", comment: "Alert OK button"),
      style: .cancel,
      handler: nil
    ))
    
    UIViewController.topMost?.present(alertController, animated: true, completion: nil)
  }
}
